package com.mulder.study.netty;

import org.apache.log4j.Logger;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;

public class NettyCommonUtil
{
    private static Logger logger = Logger.getLogger(NettyCommonUtil.class);
    
    public static void sendResponse(Channel channel, byte[] msg) throws Exception 
    {
        ChannelBuffer response =   ChannelBuffers.buffer(msg.length);
        
        response.writeBytes(msg);
        
        if(channel != null && channel.isConnected()) 
        {
            channel.write(response);
            
//            channel.write(response).addListener (new ChannelFutureListener() 
//            {
//                public void operationComplete(ChannelFuture future) 
//                {
//                    
//                }
//            });    
        } 
        else 
        {
            logger.warn("target channel closed:" + channel.getId());
        }
    }
    
    public static byte[] joinBytes (byte[] src1, byte[] src2) 
    {
        byte[] joined = new byte[src1.length + src2.length];
        
        System.arraycopy(src1, 0, joined, 0,           src1.length);
        System.arraycopy(src2, 0, joined, src1.length, src2.length);
        
        return joined;
    }
}
